package com.xnx3.kefu.chat.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.xnx3.BaseVO;
import com.xnx3.Lang;
import com.xnx3.j2ee.controller.BaseController;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.AttachmentUtil;
import com.xnx3.j2ee.vo.UploadFileVO;

/**
 * 文件上传
 * @author 管雷鸣
 *
 */
@Controller(value="KefuChatFileController")
@RequestMapping("/kefu/chat/file/")
public class FileController extends BaseController {
	
	/**
	 * 上传图片
	 * @param file 上传的图片文件
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadImage${api.suffix}",method = {RequestMethod.POST})
	public UploadFileVO uploadImage(HttpServletRequest request) {
		UploadFileVO vo = AttachmentUtil.uploadImage("kefu/extend/image/", request, "file", 0);
		//日志记录
		ActionLogUtil.insertUpdateDatabase(request,  "上传图片",vo.toString());
		return vo;
	}
	
	/**
	 * 上传录音的音频文件
	 * @param multipartFile 上传的wav音频文件
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadAudio${api.suffix}",method = {RequestMethod.POST})
	public UploadFileVO uploadAudio(HttpServletRequest request,
			@RequestParam("file") MultipartFile multipartFile) {
		UploadFileVO vo;
		try {
			vo = AttachmentUtil.uploadFile("kefu/extend/audio/"+Lang.uuid()+".wav", multipartFile.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
			vo = new UploadFileVO();
			vo.setBaseVO(UploadFileVO.NOTFILE, e.getMessage());
			return vo;
		}
		
		//日志记录
		ActionLogUtil.insertUpdateDatabase(request,  "上传图片",vo.toString());
		return vo;
	}
	

	/**
	 * 上传文件，发送文件
	 * @param multipartFile 上传的文件，form表单上传文件，其中input name 为 file
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadFile${api.suffix}",method = {RequestMethod.POST})
	public UploadFileVO uploadFile(HttpServletRequest request,
			@RequestParam("file") MultipartFile multipartFile) {
		UploadFileVO vo = AttachmentUtil.uploadFile("kefu/extend/file/", multipartFile);
		if(vo.getResult() - BaseVO.SUCCESS == 0){
			vo.setFileName(multipartFile.getOriginalFilename());
		}
		
		//日志记录
		ActionLogUtil.insertUpdateDatabase(request,  "上传文件",vo.toString());
		return vo;
	}
	
}
